import { map, marker, navi, poi, url } from "@/store";
import { bookshelfFidList } from "./enum";

class websocket {
  wssUrl: string;
  webSocket: WebSocket | null = null;
  isConnect: boolean = false; // 是否已经连接
  timeoutNumber: number = 1; // 心跳检测间隔
  heartbeatTimer: any = null; // 心跳检测定时器
  reconnectTimer: any = null; // 断线重连定时器
  isInitiative: boolean = false; // 是否主动断开
  againTime: number = 3; // 重连等待时间(单位秒)

  constructor(wssUrl: any) {
    this.wssUrl = wssUrl;
    this.initWebSocket();
  }

  initWebSocket() {
    //建立连接
    this.webSocket = new WebSocket(this.wssUrl);
    //连接成功
    this.webSocket.onopen = this.webSocketOnOpen;
    //接收信息
    this.webSocket.onmessage = this.webSocketOnMessage;
    //连接关闭
    this.webSocket.onclose = this.webSocketOnClose;
    //连接错误
    this.webSocket.onerror = this.webSocketOnError;
    //心跳检测
    this.heartbeatCheck();
  }

  webSocketOnOpen() {
    this.isConnect = true;
    console.log("WebSocket 连接成功");
  }

  webSocketSendPos() {
    // 向ws发送消息获取定位
    if (this.webSocket?.readyState == 1) {
      let msg = {
        type: "getpos",
        openId: url.openid,
        mapId: map.getLocationMapID,
      };
      // console.log("getpos:", msg)
      this.webSocket.send(JSON.stringify(msg));
    }
  }

  webSocketOnMessage(event: { data: string }) {
    navi.lastPoiTime = new Date().getTime();
    let data = JSON.parse(event.data);
    // console.log("position:", data);
    if (
      navi.status &&
      data.floorId === 4 &&
      bookshelfFidList.indexOf(url.fid) > -1 &&
      map.isContain(data)
    ) {
      //TODO:书架区域判断
      // 导航状态中进入aoa区域，弹aoa窗提醒
      map.isInAoA = true;
      map.aoaFlag = true;
      map.menuFlag = false;

      navi.curPosition = {
        x: +data.x,
        y: +data.y,
        floorId: data.floorId,
        level: data.floorId,
      };
    } else if (parseInt(data.floorId) > 0 && data.code == 1) {
      //TODO:code:0定位成功，1定位失败
      // 进入蓝牙区域
      navi.curPosition = {
        x: +data.x,
        y: +data.y,
        floorId: data.floorId,
        level: data.floorId,
      };

      if (map.status.map.load) {
        if (navi.firstCenterFlag && navi.moveLocationFlag) {
          // 第一次初始化当前位置marker
          marker.setLocationMarker(navi.curPosition);
          navi.firstCenterFlag = false;
        } else {
          // 非导航状态下，定时更新当前坐标
          navi.moveLocationCenter();
          poi.setNowPoi(navi.curPosition);
        }
      }
    }
  }

  reconnect() {
    // 停止发送心跳
    clearTimeout(this.reconnectTimer);
    clearInterval(this.heartbeatTimer);
    console.log("reconnect是否人为断开", this.isInitiative);
    // 如果不是人为关闭的话，进行重连
    // if (!this.isInitiative) {
    this.reconnectTimer = setTimeout(() => {
      this.initWebSocket();
    }, this.againTime * 1000);
    // }
  }

  webSocketOnClose() {
    console.log("WebSocket 关闭了");
    this.reconnect();
  }

  webSocketOnError(err) {
    this.isInitiative = false;
    console.log("WebSocket 出错了", err);
  }

  heartbeatCheck() {
    // 心跳检测，检测ws是否正在连接
    this.heartbeatTimer = setInterval(() => {
      this.webSocketSendPos();
      // if ((new Date().getTime() - navi.lastPoiTime) / 1000 > 2) {
      //   this.closeWebSocket();
      // }
    }, this.timeoutNumber * 1000);
  }

  closeWebSocket() {
    this.isInitiative = true;
    this.webSocket?.close();
    clearTimeout(this.reconnectTimer);
    clearInterval(this.heartbeatTimer);
    this.webSocket = null;
    this.isConnect = false;
  }
}

export default websocket;
